package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.jersey.json.impl.provider.entity.JSONArrayProvider;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmUserDto;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.common.AppJwtUtil;
import com.usian.wemedia.mapper.WmUserMapper;
import com.usian.wemedia.service.WmUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Override
    public ResponseResult add(WmUser user) {

        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
        }

        boolean save = save(user);

        if (save){
            return ResponseResult.okResult(save);
        }else {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
    }

    @Override
    public WmUser findByUserName(String name) {

        if (StringUtils.isBlank(name)){
            return null;
        }

        QueryWrapper<WmUser> wrapper = new QueryWrapper();

        wrapper.like("name",name);

        List<WmUser> list = list(wrapper);

        if (list.size()==1){
            return list.get(0);
        }else {
            return null;
        }


    }

    @Override
    public ResponseResult login(WmUserDto dto) {
        //检查参数
        if (StringUtils.isBlank(dto.getName()) || StringUtils.isBlank(dto.getPassword())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //查询数据库中数据
        QueryWrapper<WmUser> wrapper = new QueryWrapper<>();

        wrapper.lambda().eq(WmUser::getName, dto.getName());

        List<WmUser> list = list(wrapper);

        if (list!=null && list.size()==1){
            WmUser wmUser = list.get(0);

            String s = DigestUtils.md5DigestAsHex((dto.getPassword() + wmUser.getSalt()).getBytes());

            if (s.equals(wmUser.getPassword())){
                Map<String,Object> map = new HashMap<>();
                map.put("token", AppJwtUtil.getToken(wmUser.getId().longValue()));
                wmUser.setPassword("");
                wmUser.setSalt("");
                map.put("user",wmUser);

                return ResponseResult.okResult(map);
            }
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);


    }
}
